package com.shelpe.services.sinbad.controller.actionLog.impl.campaign;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import com.shelpe.services.sinbad.controller.actionLog.ActionLogDto;
import com.shelpe.services.sinbad.controller.actionLog.ActionLogService;
import com.shelpe.services.sinbad.controller.actionLog.CampaignVo;
import com.shelpe.services.sinbad.entity.jpa.AreaList;
import com.shelpe.services.sinbad.entity.jpa.Campaign;
import com.shelpe.services.sinbad.entity.jpa.CampaignLog;

@Service
public class CampaignUpdateAreaConverter extends ActionLogService {
	@Autowired
	private MessageSource messageSource;

	@Override
	public ActionLogDto convertCampaign(CampaignLog entity, Map<Long, Campaign> campaignMap, List<AreaList> areas) {
		boolean campaignUpdateAreaConverter = entity.getAction() == CampaignLog.Action.AUTO_UPDATE_AREA
				|| entity.getAction() == CampaignLog.Action.UPDATE_AREA;
		if (campaignUpdateAreaConverter && StringUtils.isNotBlank(entity.getNote())) {
			ActionLogDto dto = new ActionLogDto();
			dto.from(entity);
			Campaign campaign = campaignMap.get(entity.getCampaignID());
			CampaignVo vo = this.unserializeCampaign(entity.getNote());
			if (campaign != null && vo != null) {
				String[] params = { campaign.getTitle(), this.from(areas, vo.getAddArea().getNums()),
						this.from(areas, vo.getLessArea().getNums()) };
				dto.setReason(messageSource.getMessage("message.campaign.area.reason", params, Locale.ENGLISH));
				return dto;
			}
		}
		return null;
	}

	private String from(List<AreaList> areas, List<Integer> nums) {
		StringBuffer buff = new StringBuffer();
		Map<Long, AreaList> map = new HashMap<Long, AreaList>();
		for (AreaList area : areas) {
			map.put(area.getAreaID(), area);
		}
		if (nums != null && nums.size() > 0){
			for (int num : nums) {
				AreaList area = map.get((long)num);
				if (area != null) {
					buff.append(area.getName());
					buff.append(",");
				}
			}
		}else {
			buff.append("无");
			buff.append(",");
		}
		return buff.substring(0, buff.lastIndexOf(","));
	}
}
